package com.pioneer.fationservice.serviceinfos;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import net.tsz.afinal.FinalActivity;
import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.annotation.view.ViewInject;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.AnimationSet;
import android.view.animation.LinearInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.pioneer.fationservice.R;
import com.pioneer.fationservice.adapters.CollectionAdapter;
import com.pioneer.fationservice.adapters.CollectionAdapter.OnCollectClickListener;
import com.pioneer.fationservice.commons.SystemData;
import com.pioneer.fationservice.commons.SystemHttpURL;
import com.pioneer.fationservice.entries.CollectInfoListEntry;
import com.pioneer.fationservice.helpers.PhoneHelper;
import com.pioneer.fationservice.models.CollectInfoListModel;
import com.pioneer.fationservice.models.ResponseObject;
import com.pioneer.fationservice.parsers.BaseParser;
import com.pioneer.fationservice.parsers.CollectInfoListParser;

/**
 * 我的收藏页面
 * @author Mrper
 *
 */
public class CollectionActivity extends FinalActivity {
	
	@ViewInject(id=R.id.layout_actionbar_txtTitle) 
	private TextView txtTitle;//标题文本栏
	@ViewInject(id=R.id.activity_collection_imgBack,click="onBackClick")
	private ImageView imgBack;//返回
	@ViewInject(id=R.id.activity_collection_vIndictor)
	private View vIndictor;//指示器
	@ViewInject(id=R.id.activity_collection_txtFood,click="onTitleClick") 
	private TextView txtFood;//美食
	@ViewInject(id=R.id.activity_collection_txtHotel,click="onTitleClick") 
	private TextView txtHotel;//酒店
	@ViewInject(id=R.id.activity_collection_txtTourist,click="onTitleClick") 
	private TextView txtTourist;//景点
	@ViewInject(id=R.id.activity_collection_txtRepirAddr,click="onTitleClick") 
	private TextView txtRepairAddr;//维修点
	@ViewInject(id=R.id.activity_collection_plLst,click="onTitleClick") 
	private PullToRefreshListView plLst;//刷新列表控件
	@ViewInject(id=R.id.activity_collection_txtTip)
	private TextView txtEmptyView;//列表提示文字
	
	private int titleSelectedIndex = 0;//标题的选中项
	private int distanceToMove = 0;//每格移动的距离
	private int flag = 1;//商家类型  1为美食，2为酒店，3为景点，4为维修点  
	private List<CollectInfoListEntry> collectInfList = new ArrayList<CollectInfoListEntry>();//商家收藏列表
	private CollectionAdapter collectAdapter;//收藏列表的适配器
	private int pageIndex = 0;//当前请求的页码
	private ProgressDialog dialog;//进度提示条
	
	@Override                                                                      
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_collection);
		txtTitle.setText("我的收藏");
		distanceToMove = PhoneHelper.getScreenInfo(this).widthPixels/4;//计算每格移动的距离
		LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams)vIndictor.getLayoutParams();
		lp.width = distanceToMove;//重新计算指示器的宽度
		vIndictor.setLayoutParams(lp);
		plLst.setMode(Mode.PULL_FROM_END);//可上拉、下啦
		plLst.setDividerDrawable(new ColorDrawable(Color.GRAY));
		plLst.setOnRefreshListener(new OnRefreshListener<ListView>() {
			@Override
			public void onRefresh(PullToRefreshBase<ListView> refreshView) {
				pageIndex = 0;
				clearCollectList();//清空收藏列表
				requestCollectShopList(pageIndex+1,false);//请求商家列表
			}
		});
		collectAdapter = new CollectionAdapter(this, collectInfList,new OnCollectClickListener() {
			@Override
			public void onCollectClick(int shopId, int position) {
				requestCancelCollectShop(shopId,position);//请求取消该商家的收藏
			}
		});
		plLst.setAdapter(collectAdapter);
		plLst.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
				final CollectInfoListEntry item = collectInfList.get(position-1);
				Intent intent = new Intent(CollectionActivity.this,ShopDetailActivity.class);
				intent.putExtra("shopId", item.shopId);
				intent.putExtra("flag", flag);
				startActivity(intent);
				overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
			}
		});
		txtEmptyView.setText("您当前没有收藏任何东西");
		plLst.setEmptyView(txtEmptyView);
		requestCollectShopList(1,true);//请求商家列表
	}
	
	/**
	 * 标题点击事件
	 * @param view
	 */
	public void onTitleClick(View view){
		final int lastSelection = titleSelectedIndex;//获取上一次的索引
		switch(view.getId()){
		case R.id.activity_collection_txtFood:
			titleSelectedIndex = 0;
			flag = 1;
			break;
		case R.id.activity_collection_txtHotel:
			titleSelectedIndex = 1;
			flag = 2;
			break;
		case R.id.activity_collection_txtTourist:
			titleSelectedIndex = 2;
			flag = 3;
			break;
		case R.id.activity_collection_txtRepirAddr:
			titleSelectedIndex = 3;
			flag = 4;
			break;
		}
		vIndictor.startAnimation(getIndictorAnimation(lastSelection));//执行指示器动画
		clearCollectList();//清空收藏列表
		pageIndex = 0;//请求商家列表
		requestCollectShopList(pageIndex+1,true);
	}
	
	/**
	 * 清空收藏列表
	 */
	public void clearCollectList(){
		collectInfList.clear();
		collectAdapter.notifyDataSetChanged();
	}
	
	/**
	 * 返回操作
	 * @param view
	 */
	public void onBackClick(View view){
		this.finish();
		overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_BACK){
			imgBack.performClick();//模拟点击返回按钮
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
	
	/**
	 * 获取指示器的动画
	 * @param lastSelection
	 * @return
	 */
	public AnimationSet getIndictorAnimation(int lastSelection){
		AnimationSet anim = new AnimationSet(true);
		TranslateAnimation tranAnim = new TranslateAnimation(TranslateAnimation.ABSOLUTE, lastSelection*distanceToMove,
				TranslateAnimation.ABSOLUTE, titleSelectedIndex*distanceToMove, TranslateAnimation.ABSOLUTE,
				0, TranslateAnimation.ABSOLUTE, 0);
		anim.addAnimation(tranAnim);
		anim.setDuration(400);
		anim.setFillAfter(true);
		anim.setInterpolator(new LinearInterpolator());
		return anim;
	}
	
	/**
	 * 请求收藏商家列表
	 */
	public void requestCollectShopList(final int pageIndex,final boolean isFirstQuery){
		txtEmptyView.setText("");
		final Activity activity = this;
		if(isFirstQuery) dialog = ProgressDialog.show(activity, "", "正在获取数据");
    	FinalHttp finalHttp = new FinalHttp();
    	finalHttp.configCharset("UTF-8");
    	finalHttp.configTimeout(10*1000);
    	finalHttp.addHeader("Content-Type", "html/text");
    	finalHttp.addHeader("Conection", "Keep-Alive");
    	finalHttp.addHeader("Cache-Control", "no-cache");
    	HashMap<String,String> params = new HashMap<String,String>();
    	params.put("p", String.valueOf(pageIndex));
    	params.put("uid", String.valueOf(SystemData.uid));
    	params.put("f",String.valueOf(flag));
    	params.put("authkey", SystemData.HTTP_KEY);
    	finalHttp.post(SystemHttpURL.URL_SHOP_COLLECT_LIST, new AjaxParams(params),new AjaxCallBack<String>(){
    		@Override
    		public void onFailure(Throwable t, int errorNo, String strMsg) {
    			super.onFailure(t, errorNo, strMsg);
    			if(dialog!=null) dialog.dismiss();
    			if(plLst.isRefreshing()) plLst.onRefreshComplete();
    			txtEmptyView.setText("您当前没有收藏任何东西");
    			Toast.makeText(activity, "网络错误，请重试!", Toast.LENGTH_SHORT).show();
    		}
    		@Override
    		public void onSuccess(String str) {
    			super.onSuccess(str);
    			if(dialog!=null) dialog.dismiss();
    			System.out.println("获取收藏商家列表信息----返回信息："+str);
    			txtEmptyView.setText("您当前没有收藏任何东西");
    			CollectInfoListModel model = (CollectInfoListModel) new CollectInfoListParser(str).getResponseObject();
    			switch(model.status){
    			case 1:
    				collectInfList.addAll(model.collectionInfoList);
    				collectAdapter.notifyDataSetChanged();
    				CollectionActivity.this.pageIndex = pageIndex;//成功后获取当前页码
    				break;
    			case 0:
    				Toast.makeText(activity, model.msg, Toast.LENGTH_SHORT).show();
    				break;
    			}
    			if(plLst.isRefreshing()) plLst.onRefreshComplete();
    		}
    	});
	}	
	
	/**
	 * 请求收藏信息
	 */
	public void requestCancelCollectShop(final int shopId,final int position){
		final ProgressDialog dialog = ProgressDialog.show(this, "", "请稍等...");
		FinalHttp finalHttp = new FinalHttp();
    	finalHttp.configCharset("UTF-8");
    	finalHttp.configTimeout(10*1000);
    	finalHttp.addHeader("Content-Type", "html/text");
    	finalHttp.addHeader("Conection", "Keep-Alive");
    	finalHttp.addHeader("Cache-Control", "no-cache");
    	HashMap<String,String> params = new HashMap<String,String>();
    	params.put("uid", String.valueOf(SystemData.uid));
    	params.put("sid", String.valueOf(shopId));
    	params.put("f",String.valueOf(0));
    	params.put("authkey", SystemData.HTTP_KEY);
    	finalHttp.post(SystemHttpURL.URL_SHOP_COLLECT, new AjaxParams(params),new AjaxCallBack<String>(){
    		@Override
    		public void onFailure(Throwable t, int errorNo, String strMsg) {
    			super.onFailure(t, errorNo, strMsg);
    			if(dialog!=null) dialog.dismiss();
    			Toast.makeText(CollectionActivity.this, "取消收藏失败，请重试!", Toast.LENGTH_SHORT).show();
    		}
    		@Override
    		public void onSuccess(String str) {
    			super.onSuccess(str);
    			if(dialog!=null) dialog.dismiss();
    			ResponseObject model = (new BaseParser(ResponseObject.class,str){
					@Override
					public void parseJSONModels(Object jsonModels,boolean isJSONObject) {
					}
				}).getResponseObject();
    			if(model.status == 1){
    				//移除该项收藏
    				collectInfList.remove(position);
    				collectAdapter.notifyDataSetChanged();
    			}
    			Toast.makeText(CollectionActivity.this, model.status == 1?"取消收藏成功!":model.msg,
						Toast.LENGTH_SHORT).show();
    		}
    	});
	}
	
	
}
